package com.example.luke.shengdangxiaoattendance;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.luke.shengdangxiaoattendance.Common.CommonActivity;
import com.example.luke.shengdangxiaoattendance.Database.DingHanDB;
import com.example.luke.shengdangxiaoattendance.Model.App;
import com.example.luke.shengdangxiaoattendance.Model.Course;
import com.example.luke.shengdangxiaoattendance.Model.Student;
import com.example.luke.shengdangxiaoattendance.Util.ExcelUtils;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;
import com.example.luke.shengdangxiaoattendance.Util.ZYScanner;
import com.example.luke.shengdangxiaoattendance.http.HttpClient;
import com.example.luke.shengdangxiaoattendance.http.HttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

public class MainActivity extends CommonActivity {

    @InjectView(R.id.currentTime)TextView currentTime;
//    @InjectView(R.id.climate)   TextView climate;
//    @InjectView(R.id.temperature)TextView temperature;
//    @InjectView(R.id.airDirection)TextView airDirection;
    @InjectView(R.id.todayDate)TextView todayDate;
   @InjectView(R.id.weekDay)TextView weekDay;


    @InjectView(R.id.name1)TextView name1;
    @InjectView(R.id.time)TextView time;
    @InjectView(R.id.name2)TextView name2;
    @InjectView(R.id.teacher)TextView teacher;

    @InjectView(R.id.className)TextView className;


    @InjectView(R.id.totalStudent)TextView totStudent;
    @InjectView(R.id.presentStudent)TextView preStudent;
    @InjectView(R.id.absentStudent)TextView abStudent;

    @InjectView(R.id.container_title_bar)LinearLayout containerTit;


    private Course currentCourse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.center_main_container);



        initNFCParam();
        getWeatherDetail();

        initView();

        if(    ExcelUtils.verifyStoragePermissions(this) ){

            ExcelUtils.creatDir(this,"省党校");
            setUpFile();

        }

      requestUsbPermission();

      reqDataFromHttp();

   //  gotoDetailCont("4");
//       GlobalFunction.printTextByTag( getDatabasePath("DingHan.db").toString() );
//
//        String startTime=GlobalFunction.convertDate(currentCourse.getStartTime(),"HH:mm");
//        //GlobalFunction.printTextByTag(new Date()+"-"+currentCourse.getStartTime());
//        GlobalFunction.printTextByTag(startTime);
    }

    private void reqDataFromHttp(){

        HashMap<String,String>param =new HashMap<>();
        param.put("KCDD","海兴102教室");
        param.put("KSSJ","2017/01/10 8:00:00");
        param.put("JSSJ","2017/01/10 14:00:00");


        HttpClient.post("http://172.20.3.13/webapi/api/GetCourseInfo",null, new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);

            GlobalFunction.printTextByTag("suc:responseBody"+statusCode+":"+responseBody);

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.printTextByTag("fail:responseBody"+e.getMessage());
            }
        });
    }
    private void setUpFile(){


//        if (Course.getInstance(this).getCourseArrayList().size()==0){
//
//
//        }
//        else {
//
//            setUpCourseContent();
//
//        }

        ExcelUtils.getFileList(this);


        setUpCourseContent();
        ExcelUtils.initStudentList(context);


    }

    private  void setUpCourseContent(){

        try {



            currentCourse=Course.getInstance(this).getCurrentCourse();
         //   GlobalFunction.printTextByTag("init course"+currentCourse);

            if (currentCourse!=null)
            {
                initCurrentCourseData();

                reloadStudentCount();

            }

            else{

                GlobalFunction.printTextByTag("没课");
                GlobalFunction.ToastAlert(this,"暂时没课");
            }


        }catch (Exception e){
            GlobalFunction.printTextByTag(e.getMessage());
        }


    }
    private void initCurrentCourseData(){


         name1.setText(currentCourse.name1);
         name2.setText(currentCourse.name2);
         time.setText(currentCourse.Time);
         teacher.setText(currentCourse.teacher);
         className.setText(currentCourse.className);
         weekDay.setText(GlobalFunction.getWeekDay());

         App.getInstance().currentCourse=currentCourse;

    }




    @Override
    public void initView() {
        super.initView();
        ButterKnife.inject(this);
        currentTime.setText(GlobalFunction.getTimeWithFomat(new Date(), "HH:mm:ss"));
        todayDate.setText(GlobalFunction.getTimeWithFomat(new Date(), "MM月dd日"));

        zyScanner.startRead();
        zyScanner.setZyListener(new ZYScanner.ZYListener() {
            @Override
            public void getCardInfo(Double reduceAmount, Double remain, Double currentBalance) {

            }

            @Override
            public void getMICardNo(String cardNo, String ticketID) {
                int temp=Integer.valueOf(cardNo);

                GlobalFunction.printTextByTag("callback Card" + Integer.valueOf(cardNo));
                if (temp==0){

                    GlobalFunction.printTextByTag("error");
                    GlobalFunction.ToastAlert(MainActivity.this,"请重新读卡");

                    zyScanner.startRead();

                }else {

                    if (currentCourse!=null)
                        gotoDetailCont(cardNo);

                    else
                        GlobalFunction.ToastAlert(MainActivity.this,"请在开始上课期间才开始刷卡");
                }



            }

            @Override
            public void showFixPurchaseCost(Double cost) {

            }

            @Override
            public void finishRead() {

             zyScanner.startRead();

            }
        });

        new Thread(){
            @Override
            public void run() {
                super.run();

                Timer  timer =new Timer();
                timer.schedule(new ReloadView(),0,1000);

            }
        }.start();

        containerTit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(SettingActivity.class);

                      GlobalFunction.printTextByTag("c");

            }
        });
    }

    private void gotoDetailCont(String cardNo){

        Student respObj=DingHanDB.getInstance(this).getCorrespondingStudent(cardNo);

        if (respObj!=null){
            String startTime=GlobalFunction.convertDate(currentCourse.getStartTime(),"HH:mm");
            String endTime=GlobalFunction.convertDate(currentCourse.getEndTime(),"HH:mm");

        try {

            if (GlobalFunction.getHourMinDifference(new Date(),currentCourse.getStartTime())<=60 ||
                    GlobalFunction.isTimeBetweenTwoTime(startTime,endTime))//只能提前一个小时读卡
            {

               if (className.getText().toString().contains(respObj.className)){

                    App.getInstance().selectedStudent=respObj;
//                    App.getInstance().climate=climate.getText().toString();
//                    App.getInstance().airDirection=airDirection.getText().toString();
//                    App.getInstance().temperature=airDirection.getText().toString();
                    App.getInstance().totalStudent=totStudent.getText().toString();
                    App.getInstance().preStudent=preStudent.getText().toString();
                    App.getInstance().currentCourse=currentCourse;


                    gotoActivity(DetailActivity.class);

                }else {

                    zyScanner.startRead();
                    GlobalFunction.ToastAlert(this,"你不属于当前班级学生");
                }



            }else {

                    GlobalFunction.ToastAlert(this,"只能提前一个小时刷卡");
                zyScanner.startRead();


            }

        }catch (Exception e){

        }




        }else
        {
            GlobalFunction.ToastAlert(this,"此卡未登记过");
            zyScanner.startRead();
        }





    }

    private  boolean checkIsLate(){

    try {
        return new Date().after(currentCourse.getStartTime());

     }catch (Exception e){

        return false;

     }



    }

    public  void getWeatherDetail(){

        HttpClient.get("http://wthrcdn.etouch.cn/weather_mini?city=广州",null,new HttpResponseHandler(){

            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);
                try {

                    JSONObject object= new JSONObject(responseBody);
                    JSONObject data= new JSONObject( object.getString("data") );

                    JSONArray forecast=data.getJSONArray("forecast");

                   filterWeatherArray(forecast);

                }
                catch (Exception e){

//                    GlobalFunction.printTextByTag(e.getMessage());
                }
              GlobalFunction.printTextByTag(responseBody);
            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.printTextByTag(e.getMessage());
            }
        });
    }


    public  void filterWeatherArray (JSONArray array) throws JSONException {

        String todayDay = GlobalFunction.getTimeWithFomat(new Date(), "dd");
        JSONObject respObj=null;

        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            String day = object.getString("date");

            if (day.contains(todayDay)){
                respObj=object;

                break;

            }
        }

        String highTemp=respObj.getString("high").split(" ")[1];
        String lowTemp=respObj.getString("low").split(" ")[1];

//        climate.setText(respObj.getString("type"));
//        temperature.setText(lowTemp+"~"+highTemp);
//        airDirection.setText(respObj.getString("fengxiang"));

    }


    public void reloadStudentCount(){
       String[] classes= className.getText().toString().split(",");
        int temp=0;
        for (String str:classes){

            int c= DingHanDB.getInstance(this).getStudentCountForClass(str.trim());

            temp=temp+c;

        }

        int preStudentCount=App.getInstance().getTotalStudentForCurrentClass();

        totStudent.setText(temp+"");
        abStudent.setText(temp-preStudentCount+"");
        preStudent.setText(preStudentCount+"");

    }

    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        reloadStudentCount();
        zyScanner.startRead();

    }


    class ReloadView extends TimerTask{
        @Override
        public void run() {

        runOnUiThread(new Runnable() {

     @Override
    public void run() {

        setUpCourseContent();

        currentTime.setText(GlobalFunction.getTimeWithFomat(new Date(), "HH:mm:ss"));

            }
        });

        }
    }
}
